import 'package:flutter/material.dart';
import 'package:github_client_flutter/index.dart';

class HomeRoute extends StatefulWidget {
  const HomeRoute({super.key});

  @override
  State<HomeRoute> createState() => _HomeRouteState();
}

class _HomeRouteState extends State<HomeRoute> {
  static const loadingTag = "##loading##";
  final _items = <Repo>[Repo()..name = loadingTag];
  bool hasMore = true;
  int page = 1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(GmLocalizations.of(context).home),
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    UserModel userModel = Provider.of(context);
    final GmLocalizations gm = GmLocalizations.of(context);
    print(userModel.isLogin);
    if (!userModel.isLogin) {
      return Center(
        child: ElevatedButton(
          child: Text(gm.login),
          onPressed: () => Navigator.of(context).pushNamed('login'),
        ),
      );
    } else {
      return ListView.separated(
        itemBuilder: (context, index) {
          if (_items[index].name == loadingTag) {
            if (hasMore) {
              _retrieveData();
              return Container(
                padding: const EdgeInsets.all(16.0),
                alignment: Alignment.center,
                child: const SizedBox(
                  width: 24.0,
                  height: 24.0,
                  child: CircularProgressIndicator(
                    strokeWidth: 2.0,
                  ),
                ),
              );
            } else {
              return Container(
                alignment: Alignment.center,
                padding: const EdgeInsets.all(16.0),
                child: const Text(
                  "没有更多了",
                  style: TextStyle(color: Colors.green),
                ),
              );
            }
          }
          return RepoItem(_items[index]);
        },
        separatorBuilder: (context, index) => const Divider(height: 0),
        itemCount: _items.length,
      );
    }
  }

  Widget MyDrawer() {
    return const Drawer(
      child: Text("Drawer"),
    );
  }

  void _retrieveData() async {
    var data = await Git(context).getRepos(queryParameters: {
      "page": page,
      "page_size": 20,
    });
    hasMore = data.isNotEmpty && data.length % 20 == 0;
    setState(() {
      _items.insertAll(_items.length - 1, data);
      page++;
    });
  }
}
